﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MemoLib.Tasks;
using MemoLib;

namespace UI
{
    public partial class frmTodayTask : Form
    {
        public frmTodayTask()
        {
            InitializeComponent();
        }

        public frmTodayTask(DataGridView pDgvOnce, DataGridView pDgvCycle)
        {
            this.dgvCycle = pDgvCycle;
            this.dgvOnce = pDgvOnce;

            InitializeComponent();
        }

        private DataGridView dgvOnce = null;
        private DataGridView dgvCycle = null;
        private List<TaskCard> tasks = new List<TaskCard>();

        private void GetTodayTaskList()
        {
            foreach (DataGridViewRow row in this.dgvOnce.Rows)
            {
                OnceTaskCard onceTaskCard = Utility.ConvertCellToOnceTaskCard(row.Cells);
                
                // 下次执行时间或者上次执行时间的日期和今天日期一致，即可判断是今天任务（可能是已经执行完毕的任务）
                if (IsTodayTask(onceTaskCard))
                {
                    this.tasks.Add(onceTaskCard);
                }
            }
            foreach (DataGridViewRow row in this.dgvCycle.Rows)
            {
                CycleTaskCard cycleTaskCard = Utility.ConvertCellToCycleTask(row.Cells);
                if (IsTodayTask(cycleTaskCard))
                {
                    this.tasks.Add(cycleTaskCard);
                }
            }

            this.dgvTodayList.DataSource = this.tasks;
        }

        private bool IsTheSameDay(DateTime dt1, DateTime dt2)
        {
            return dt1.Year == dt2.Year && dt1.Month == dt2.Month && dt1.Day == dt2.Day;
        }

        private bool IsTodayTask(TaskCard pTaskCard)
        {
            DateTime exeDate = pTaskCard.ExecuteDateTime;
            DateTime lastExeDate = pTaskCard.LastExecuteDateTime.HasValue ? pTaskCard.LastExecuteDateTime.Value : DateTime.MinValue;
            DateTime today = DateTime.Now;

            return IsTheSameDay(exeDate, today) || IsTheSameDay(lastExeDate, today);
        }

        private void frmTodayTask_Load(object sender, EventArgs e)
        {
            this.GetTodayTaskList();
        }
    }
}
